package com.jinlia.show.common.core.utils;

import com.jinlia.show.common.core.exception.MyRuntimeException;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UserInfoUtils {

    public static String getUserName() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String authorization = request.getHeader("authorization");
        String username = JavaJwtUtils.decode(authorization).getClaim("username").asString();
        return username;
    }
    public static Long getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String authorization = request.getHeader("authorization");
        if (StringUtils.isEmpty(authorization)) {
            return 0l;
        }
        Long userId = JavaJwtUtils.decode(authorization).getClaim("userId").asLong();
        return userId;
    }
    public static String getOpenid() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String authorization = request.getHeader("authorization");
        if (StringUtils.isEmpty(authorization)) {
            return "0l";
        }
        String openid = JavaJwtUtils.decode(authorization).getClaim("openid").asString();
        return openid;
    }
    public static String getAppId() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String authorization = request.getHeader("authorization");
        if (StringUtils.isEmpty(authorization)) {
            throw new MyRuntimeException("方法使用不正确!!!");
        }
        String appId = JavaJwtUtils.decode(authorization).getClaim("appId").asString();
        return appId;
    }
}
